﻿using WFBot.Framework.Infrastructure;

namespace WFBot.Framework.Services
{
    using Repositories;

    using System;
    using Domain;

    public class BotService : IBotService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IQuestionRepository _questionRepository;
        private readonly IVisitorRepository _visitorRepository;
        private readonly IResponseRepository _responseRepository;

        public BotService(IUnitOfWork unitOfWork, IQuestionRepository questionRepository, IVisitorRepository visitorRepository, IResponseRepository responseRepository)
        {
            _unitOfWork = unitOfWork;
            _questionRepository = questionRepository;
            _visitorRepository = visitorRepository;
            _responseRepository = responseRepository;
        }

        public void SaveVisitorResponse(string sessionId, Question question, string answer)
        {
            var savedQuestion = _questionRepository.GetByText(question.Text);
            if (savedQuestion == null)
            {
                _questionRepository.Add(question);
                savedQuestion = question;
            }

            var visitor = _visitorRepository.GetBySessionId(sessionId);
            if (visitor == null)
            {
                visitor = new Visitor
                {
                    SessionId = sessionId,
                    RegistrationDate = DateTime.Now,
                    Identifier = string.Empty
                };

                if (savedQuestion.IsIdentifier)
                    visitor.Identifier = answer;

                _visitorRepository.Add(visitor);
            }

            var response = new Response
            {
                Visitor = visitor,
                Question = savedQuestion,
                Answer = answer
            };

            _responseRepository.Add(response);

            _unitOfWork.Commit();
        }
    }
}
